<template>
  <div class="b-m-page">
    <div class="b-m-space">
      <div class="b-m-s-title" @click="toSpacePageHandle">
        用户空间列表
      </div>
      <div @click="spaceChangeHandle(space.spaceId, index)" class="b-m-s-item" v-for="(space,index) in spaceList" :key="space.spaceId"
           :class="{ 'active': index === spaceIndex}">
        {{ space.name }}
      </div>
    </div>

    <div class="b-m-content">
      <transition name="el-zoom-in-top">
        <el-form v-show="searchBlogVisible" inline :model="searchMBlogFrom" ref="searchMBlogFrom" @keyup.enter.native="searchBlogHandle()">
          <el-form-item prop="word" label="博客标题">
            <el-input v-model="searchMBlogFrom.word" @clear="getBlogList" placeholder="请输入博客标题" clearable></el-input>
          </el-form-item>
          <el-form-item prop="label" label="博客标记">
            <el-select v-model="searchMBlogFrom.label" @clear="getBlogList" clearable placeholder="请选择博客标记" class="blog-select">
              <el-option label="原创" value="0"></el-option>
              <el-option label="转载" value="1"></el-option>
              <el-option label="翻译" value="2"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item v-show="blogStatus === 3" prop="hot" label="是否热门">
            <el-select v-model="searchMBlogFrom.hot" @clear="getBlogList" clearable placeholder="博客热门状态" class="blog-select">
              <el-option label="热门" value="0"></el-option>
              <el-option label="正常" value="1"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button :disabled="dataLoad" @click="searchBlogHandle" type="primary" icon="el-icon-search">查询</el-button>
            <el-button :disabled="dataLoad" @click="resetBlogMPageHandle"
                       plain icon="el-icon-refresh-right">重置</el-button>
          </el-form-item>
        </el-form>
      </transition>

      <div class="b-m-tool">
        <el-radio-group v-model="blogStatus" :disabled="dataLoad" @change="blogStatusChangeHandle" size="mini">
          <el-radio-button :label="0">草稿</el-radio-button>
          <el-radio-button :label="1">审核</el-radio-button>
          <el-radio-button :label="2">下架</el-radio-button>
          <el-radio-button :label="3">发布</el-radio-button>
        </el-radio-group>
        <el-button :disabled="dataLoad" @click="openAddBlogPageHandle"
                   type="primary" size="mini" plain icon="el-icon-plus">添加博客</el-button>
        <el-button :disabled="dataLoad || blogTableSelected.length === 0" @click="deleteBlogHandle(true, undefined)"
                   type="danger" size="mini" plain icon="el-icon-delete">删除博客</el-button>

        <right-tool-bar :search-visible="searchBlogVisible"
                        @toggle-search="toggleSearch" @refresh-table="getBlogList" />
      </div>

      <el-table
        v-loading="dataLoad"
        :data="blogList"
        :default-sort = "{ prop: searchMBlogFrom.field, order: searchMBlogFrom.order}"
        @sort-change="sortChangeHandle"
        @selection-change="selectionChangeHandle"
        ref="blogMTable"
      >
        <el-table-column type="selection" header-align="center" align="center" width="50"></el-table-column>
        <el-table-column prop="title" header-align="center" align="center" label="标题"></el-table-column>
        <el-table-column prop="firstPicture" header-align="center" align="center" label="首图">
          <template v-slot="scope">
            <img :src="scope.row.firstPicture" alt="没有找到图片" class="first-picture">
          </template>
        </el-table-column>
        <el-table-column prop="label" header-align="center" align="center" label="标记">
          <template v-slot="scope">
            {{ scope.row.label === 0 ? '原创' : scope.row.label === 1 ? '转载' : '翻译' }}
          </template>
        </el-table-column>
        <el-table-column prop="showStatement" header-align="center" align="center" label="版权">
          <template v-slot="scope">
<!--            <el-tag type="info" :class="'m-statement' + scope.row.showStatement">
              {{ scope.row.showStatement == 0 ? '开启' : '关闭' }}
            </el-tag>-->
            <el-switch
              v-model="scope.row.showStatement"
              :active-color="themeColor"
              inactive-color="#ff4949"
              :active-value="0"
              :inactive-value="1"
              @change="blogFieldStatusChangeHandle($event, scope.row, false)">
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column prop="openComment" header-align="center" align="center" label="评论">
          <template v-slot="scope">
            <el-switch
              v-model="scope.row.openComment"
              :active-color="themeColor"
              inactive-color="#ff4949"
              :active-value="0"
              :inactive-value="1"
              @change="blogFieldStatusChangeHandle($event, scope.row, true)">
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column v-if="blogStatus === 3" sortable prop="likeNum" header-align="center" align="center" label="点赞数" width="90"></el-table-column>
        <el-table-column v-if="blogStatus === 3" sortable prop="commentNum" header-align="center" align="center" label="评论数" width="90"></el-table-column>
        <el-table-column v-if="blogStatus === 3" sortable prop="viewNum" header-align="center" align="center" label="浏览数" width="90"></el-table-column>
        <el-table-column v-if="blogStatus === 3" sortable prop="collectNum" header-align="center" align="center" label="收藏数" width="90"></el-table-column>
        <el-table-column v-if="blogStatus === 3" prop="isHot" header-align="center" align="center" label="热门">
          <template v-slot="scope">
            <el-tag :type="scope.row.isHot === 0 ? 'success' : 'primary'">
              {{ scope.row.isHot === 0 ? '热门' : '正常' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column v-if="blogStatus === 3" prop="isElite" header-align="center" align="center" label="推荐">
          <template v-slot="scope">
            <el-tag :type="scope.row.isElite === 0 ? 'success' : 'primary'">
              {{ scope.row.isElite === 0 ? '推荐' : '正常' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column v-if="blogStatus === 3" sortable prop="issueTime" header-align="center" align="center" label="发布时间" width="100"></el-table-column>
        <el-table-column sortable prop="createTime" header-align="center" align="center" label="创建时间" width="100"></el-table-column>
        <el-table-column
          fixed="right"
          header-align="center"
          align="center"
          width="150"
          label="操作">
          <template v-slot="scope">
            <el-button v-if="blogStatus === 0" type="text" @click="commitBlogHandle(scope.row.blogId)">上传</el-button>
            <el-button v-if="blogStatus === 1" type="text" @click="cancelBlogHandle(scope.row.blogId)">撤销</el-button>
            <el-button type="text" @click="openUpdateBlogPageHandle(scope.row.blogId)">修改</el-button>
            <el-button type="text" @click="deleteBlogHandle(false, scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 表格分页插件 -->
      <el-pagination
        @size-change="sizeChangeHandle"
        @current-change="currentChangeHandle"
        :current-page="pageIndex"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="pageSize"
        :total="totalNum"
        :disabled="dataLoad"
        layout="total, sizes, prev, pager, next, jumper"
        class="paging">
      </el-pagination>
    </div>

  </div>
</template>

<script>
  import RightToolBar from '@/components/common/right-toolbar'

  export default {
    layout: 'admin',
    name: "admin-blog-manage",
    components: { RightToolBar },
    data() {
      return {
        // 选择空间列表下标
        spaceIndex: '',
        // 用户所有空间列表
        spaceList: [],
        // 表格显示博客数据类型[0-草稿 1-审核 2-下架 3-发布]
        blogStatus: 0,
        // 博客数据列表
        blogList: [],
        // 博客表格被选中的‘行’数据
        blogTableSelected: [],
        // 数据是否加载[false-不加载 true-加载]
        dataLoad: false,
        // 博客检索是否显示
        searchBlogVisible: true,
        // 博客管理检索表单对象
        searchMBlogFrom: {
          spaceId: '',        // 博客所属空间id
          word: '',           // 博客标题或者博客前言
          label: '',          // 博客标记
          hot: '',            // 博客是否热门
          field: 'createTime',// 排序字段
          order: 'ascending'  // 排序方式
        },
        // 当前展示页码
        pageIndex: 1,
        // 当前页显示个数
        pageSize: 10,
        // 当前博客数量
        totalNum: 0,
      }
    },
    computed: {
      // 主题颜色
      themeColor() {
        return this.$store.state.settings.theme
      }
    },
    asyncData({ app, params, query}) {
      // return app.$axios.$post('/blog/blog/list', { status: params.status || 0, page: 1, limit: 10, field: 'updateTime', order: 'ascending' })
      //   .then(data => {
      //     return {
      //       blogList: data.page.list,
      //       totalNum: data.page.totalNum,
      //       blogStatus: params.status || 0
      //     }
      //   })
      return {
        blogStatus: params.status || 0
      }
    },
    created() {
      if (process.client) {
        this.getBlogList()

        this.getAllSpace()
      }
    },
    activated () {
      let params = this.$route.params
      if (typeof params.status === "number") {
        // 切换显示的博客类型
        this.blogStatus = params.status
      }
      if (!!params.refresh) {
        // 刷新博客列表
        this.getBlogList()
      }
    },
    methods: {
      // 跳转到用户空间管理页面
      toSpacePageHandle() {
        /*let obj = {
          // 菜单id
          menuId: menu.menuId,
          // 菜单路由
          path: "/" + menu.path,
          // 菜单名字标题
          title: menu.name,
          // 参数1
          params: {},
          // 参数2
          query: {}
        }
        // 添加一个菜单tab
        this.$store.commit('menu/addMenuTabOnMiss', obj)*/
        // 路由跳转
        this.$router.push('/admin/user/space')
      },
      // 获取用户所有空间信息
      getAllSpace() {
        this.$axios.$get('/blog/space/all/space')
          .then(({ data }) => {
            if (!!data) {
              this.spaceList = data
            }
          })
          .catch(() => {})
      },
      // 博客空间列表选择事件
      spaceChangeHandle(spaceId, index) {
        if (this.spaceIndex === index) {
          this.spaceIndex = ''
          this.searchMBlogFrom.spaceId = ''

        } else {
          this.spaceIndex = index
          this.searchMBlogFrom.spaceId = spaceId

        }

        this.getBlogList()
      },
      // 用户检索事件
      searchBlogHandle() {
        if (this.spaceIndex === '' && this.searchMBlogFrom.word === '' && this.searchMBlogFrom.label === ''
          && this.searchMBlogFrom.hot === '') {
          this.notify('info', "提示", '检索条件为空')
          return
        }
        this.getBlogList()
      },
      // 用户检索 显示/隐藏 事件
      toggleSearch() {
        this.searchBlogVisible = !this.searchBlogVisible
      },
      // 获取用户博客列表事件
      getBlogList() {
        let userBlogForm = {
          spaceId: this.searchMBlogFrom.spaceId,
          word: this.searchMBlogFrom.word,
          label: this.searchMBlogFrom.label,
          hot: this.searchMBlogFrom.hot,
          status: this.blogStatus,
          page: this.pageIndex,
          limit: this.pageSize,
          // 排序字段
          field: this.searchMBlogFrom.field,
          // 排序方式
          order: this.searchMBlogFrom.order
        }
        // 表格数据加载
        this.dataLoad = true
        this.$axios.$post('/blog/list', userBlogForm)
          .then(({ data:page }) => {
            this.blogList = page.list
            this.totalNum = page.totalNum
          })
          .catch(() => {})
          .finally(() => {
            // 表格加载结束
            this.dataLoad = false
          })
      },
      // 显示博客数据类型切换事件
      blogStatusChangeHandle(value) {
        this.blogStatus = value
        this.spaceIndex = ''
        this.searchMBlogFrom.spaceId = ''
        this.searchMBlogFrom.field = 'createTime'

        this.getBlogList()
      },
      // 每页显示个数变化事件
      sizeChangeHandle(size) {
        this.pageIndex = 1
        this.pageSize = size
        this.getBlogList()
      },
      // '点击特定页码'、'上一页'、'下一页'操作事件
      currentChangeHandle(index) {
        if (this.pageIndex === index) {
          return
        }
        this.pageIndex = index
        this.getBlogList()
      },
      // 表格选择字段排序事件
      sortChangeHandle( { prop, order } ) {

        if (!order) {   // 第三次点击同一个排序字段，恢复默认排序
          this.searchMBlogFrom.field = 'createTime'
          this.searchMBlogFrom.order = 'ascending' // descending
        } else {
          this.searchMBlogFrom.field = prop
          this.searchMBlogFrom.order = order
        }

        this.getBlogList()
      },
      // 博客表格行被选中事件
      selectionChangeHandle(data) {
        this.blogTableSelected = data
      },
      /**
       * 修改博客评论/博客版权状态修改事件
       * @param value 最新状态
       * @param blog  博客对象
       * @param bool  变更类型[true-博客评论 false-博客版权]
       */
      blogFieldStatusChangeHandle(value, blog, bool) {
        let obj = {
          blogId: blog.blogId,
          status: value,
          bool: bool
        }
        // 表格数据加载
        this.dataLoad = true
        this.$axios.$get('/blog/field/update', { params: obj })
          .then(() => {
            this.notify('success', '状态修改成功', bool ? '博客评论状态修改成功' : '博客版权状态修改成功')
          })
          .catch(() => {
            if (bool) {
              blog.openComment = blog.openComment === 0 ? 1 : 0
            } else {
              blog.showStatement = blog.showStatement === 0 ? 1 : 0
            }
          })
          .finally(() => {
            // 表格加载结束
            this.dataLoad = false
          })
      },
      // 跳转至博客添加页面事件
      openAddBlogPageHandle() {
        // 之后携带参数进行跳转
        this.$router.push('/admin/blog/save')
      },
      // 博客提交审核处理事件
      commitBlogHandle(blogId) {
        this.$confirm('确定要将博客提交审核吗?', '提交博客', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'info'
        }).then(() => {
          // 表格数据加载
          this.dataLoad = true
          this.$axios.$get('/blog/commit/check', { params: { blogId }})
            .then(() => {
              this.notify('success', '上传成功', '上传博客审核成功')

              this.getBlogList()
            })
            .catch(() => {})
            .finally(() => {
              // 表格加载结束
              this.dataLoad = false
            })

        }).catch(() => {});

      },
      // 取消博客审核
      cancelBlogHandle(blogId) {
          this.$confirm('确定要撤回正在审核的博客吗?', '取消审核', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'info'
          }).then(() => {
            // 表格数据加载
            this.dataLoad = true
            this.$axios.$get('/blog/withdraw/check', { params: { blogId }})
              .then(() => {
                this.notify('success', '取消成功', '取消博客审核成功，博客已放入保存列表中')

                this.getBlogList()
              })
              .catch(() => {})
              .finally(() => {
                // 表格加载结束
                this.dataLoad = false
              })
          }).catch(() => {})

      },
      // 跳转到博客更新页面事件
      openUpdateBlogPageHandle(blogId) {
        // 之后携带参数进行跳转
        this.$router.push({ name: 'admin-blog-update', params: { blogId: blogId.toString(), status: this.blogStatus.toString() }})
      },
      /**
       * 删除博客事件
       * @param optType 操作类型[false-单个删除 true-批量删除]
       * @param blog    博客对象（只有单个删除时，该参数才有值）
       */
      deleteBlogHandle(optType, blog) {
        // 所有要删除的博客id
        let blogIds = []
        // 所有要删除的博客标题
        let blogTitle = "["
        if (optType) {
          this.blogTableSelected.forEach(blog => {
            blogIds.push(blog.blogId)
            blogTitle += blog.title + ','
          })
          blogTitle = blogTitle.substring(0, blogTitle.length - 1) // 去掉最后一个‘逗号’
        } else {
          blogIds.push(blog.blogId)
          blogTitle += blog.title
        }
        blogTitle += ']'

        this.$confirm(`确定删除${blogTitle}博客吗?删除之后将无法恢复博客`, '博客删除', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          let obj = {
            blogIds: JSON.stringify(blogIds),
            status: this.blogStatus
          }
          this.$axios.$post('/blog/delete', obj)
            .then(() => {
              this.notify('success', '删除成功', `${blogTitle}博客删除成功`)
              // 清空表格选中行
              this.$refs.blogMTable.clearSelection()
              // 重新获取博客列表
              this.getBlogList()
            })
            .catch(() => {})
        }).catch(() => {})
      },
      // 重置页面事件
      resetBlogMPageHandle() {
        if (this.spaceIndex === '' && this.searchMBlogFrom.word === '' && this.searchMBlogFrom.label === ''
          && this.searchMBlogFrom.hot === '' && this.pageIndex === 1 && this.pageSize === 10) {
          this.notify('info', "提示", '检索条件为空')
          return
        }
        // 重置博客查询表单
        this.$refs['searchMBlogFrom'].resetFields()
        // 手动清空博客所属空间id
        this.searchMBlogFrom.spaceId = ''
        this.pageIndex = 1
        this.pageSize = 10
        this.spaceIndex = ''
        // console.log("表单对象: ", this.searchMBlogFrom)

        this.getBlogList()
      }
    }
  }
</script>

<!--
  css字符对应
  b -> blog
  m -> manage
-->
<style scoped>
  .b-m-page {
    position: relative;
    box-sizing: border-box;
  }
  .b-m-page:before, .b-m-page:after {
    display: table;
    content: "";
  }
  .b-m-page:after {
    clear: both;
  }
  .b-m-page .b-m-space {
    width: 20%;
    float: left;
    box-sizing: border-box;
  }
  .b-m-page .b-m-content {
    width: 78.7%;
    margin-left: 15px;
    float: left;
    box-sizing: border-box;
  }
</style>

<!-- 博客管理-左侧样式 -->
<style scoped>
  .b-m-space .b-m-s-title {
    font-size: 15px;
    margin-bottom: 10px;
    cursor: pointer;
  }
  .b-m-space .b-m-s-title:hover {
    color: #17B3A3;
  }
  .b-m-space .b-m-s-item {
    font-size: 13px;
    padding: 7px;
    cursor: pointer;
    border-radius: 2px;
  }
  .b-m-space .b-m-s-item.active {
    color: #17B3A3;
  }
  .b-m-space .b-m-s-item:hover {
    background-color: rgba(22,178,162, .1);
  }
</style>

<!-- 博客管理-右侧样式 -->
<style scoped>
  .b-m-content .blog-select {
    width: 140px;
  }
  .b-m-content .b-m-tool {
    margin-bottom: 7px;
  }
  .b-m-content .paging {
    float: right;
    margin: 7px;
  }
  .b-m-content .first-picture {
    width: 50px;
    height: 40px;
    line-height: 45px;
  }
  .b-m-content .m-statement0 {
    color: #699217;
  }
  .b-m-content .m-statement1 {
    color: #f14b4b;
  }
  .b-m-content .m-comment0 {
    color: #6CBCBC;
  }
  .b-m-content .m-comment1 {
    color: #cba457;
  }
</style>
